package com.zhengjiang.hl7;

import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.Structure;
import ca.uhn.hl7v2.model.v231.message.ACK;
import ca.uhn.hl7v2.parser.PipeParser;

public class HL7ParseUtil {

    /**
     * 解析
     * @param hl7Str
     * @return
     * @throws HL7Exception
     */
    public static Message parse(String hl7Str) throws HL7Exception {
        // 解析器
        PipeParser parser = new PipeParser();
        // 解析
        Message message = parser.parse(hl7Str);
        if (message instanceof ACK) {
            // 如果确认是ACK消息可以直接返回ACK
            return (ACK) message;
        }
        return message;
    }

    public static void main(String[] args) throws Exception {
        // HL7消息
        String hl7Str = "MSH|^~\\&|foo|foo||foo|202103151718||ORU^R01|1|P|2.4||||0|UNICODE";
//
//        String hl7Str = "MSH|^~\\&|MediII|MediInfo|WXXD|YX|20200720151947||ADT^A10^ADT_A09|cc492d953bb14b7991f73391e3775ec8|P|2.3.1\n" +
//                "PID||357778999^0|357778999^^^JG01~155484212^^^JG02~5484213565^^^JG03~~~326632365516^^^JG06~78554215^^^JG07~212545wwe^^^JG08~~4581584^^^JG10~|0|ZhangSan^张三||19440426000000|1|||北京市朝阳区xxxx街道^260005^260005^260005^260005^^H^^260005~^^^^-^^W^-~北京市朝阳区xxxx街道^260005^260005^260005^^^R||^^01^^^^18365655555~^^02|||||330227194404267517|3325626262688888|||01^汉族|北京/朝阳/xx街道|||||156^中国||0\n" +
//                "PV1|2|I|06^06^06481^0505055&胸外科一&0^^胸外科(1)病区|R|||10178^^梁三^^^^^^^^^^^0402&胸外一D组|||||||||||150|10107360||YKT301||||20210720|||||||||||||||||0505055^^^1||20200720151947||||||2|V|10178^^梁三~16388^^曹四\n" +
//                "OBX|0|NM|25^年龄||77|岁|||||F|||20200720151947\n" +
//                "DG1|1|E11.900||2型糖尿病||A\n";

            String str =
        "MSH|^~\\&|123|123|123||202103151718||0RU^R01|1|P|2.3.1||||0|UNICODE|\n"+
        "PID|1|1|002||Jack|^||M|2^Y\n" +
        "0BR|1|12345|1|Analyzer ID^XX-400|Y||20110321141811||1|E002^3||N||20110321101112|0|||||1||20110321141811|";
       /* 0BX|NH|1|ALT^1|2.31U/L| 0-40|N||C11112011 0321142155 |1|1| <CR>
                0BX |NM|2|AST^1 |35 |U/L| 0-34|H|IC| || |20110321142155 | 1|1|<CR>
                0BXINM|3| T4 ^1512.1|nm1/112.82-8.2411C111281163211421551111<CR>
                <EB><CR>*/

        // 解析为消息
        Message message = HL7ParseUtil.parse(str);
        // 输出原消息
        System.out.println(message.encode().replaceAll("\r", "\r\n"));
//        Structure msh = message.get("MSH");
//        System.out.println(msh.getMessage());
    }
}
